import requests
import os
import json
import re
from bs4 import BeautifulSoup
from django.conf import settings
import urllib.parse as urlparse

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
}

source = 'http://pic.sogou.com'
upload_url = source + '/ris_upload'
query_url = source + '/ris?'

baike_url = 'http://pic.sogou.com/ris/baike_result.jsp?query='

imgname = 'aifer.jpg'
imgpath = './tmp/aifer.jpg'

resultBaike = {"similarity": "", "name": "", "birth": "", "synop": ""}
result = {"guessWord": "", "baike": resultBaike}

def tryRequest():
    try:
        files = {'file': (imgname, open(imgpath, 'rb'), 'image/jpeg'), 'pos': (None, 'upload'),
             'uptype': (None, 'upload_pc'), 'fm': (None, 'home')}

        r = requests.post(upload_url, headers=headers, files=files)
        tmp = r.text
        # print('tmp = ', tmp)

        qurl = r.url
        print('qurl = ',qurl)

        qs = urlparse.urlparse(qurl).query
        qargs = dict([(k,v[0]) for k,v in urlparse.parse_qs(qs).items()])
        print('args = ',qargs)

        if('query' not in qargs or 'flag' not in qargs):
            print('url err: no query arg !')
            return 
        
        # imgqurl = query_url + "query=" + qargs['query'] + '&flag=' + qargs['flag'] + "&reqType=ajax&st=14&reqForm=result"
        # img_result14 = requests.get(imgqurl,headers=headers).text

        # imgqurl = query_url + "query=" + qargs['query'] + '&flag=' + qargs['flag'] + "&reqType=ajax&st=13&reqForm=result"
        # img_result13 = requests.get(imgqurl,headers=headers).text

        # imgqurl = query_url + "query=" + qargs['query'] + '&flag=' + qargs['flag'] + "&reqType=ajax&st=12&reqForm=result"
        # print('imgqurl = ',imgqurl)
        # img_result12 = requests.get(imgqurl,headers=headers).text
       
        # print('img result json = ',img_result12)

        # outhtml = open('out.html','w') 
        # outhtml.write(img_result12)
        # outhtml.close()
        imgqurl = query_url + "query=" + qargs['query'] + "&dm=0&reqType=ajax&tn=0&reqForm=result"
        img_result = requests.get(imgqurl,headers=headers).text

        tj = json.loads(img_result)
        entity = tj['entity']
        print('entity =',entity)

        if entity != None:
            sogou_baike = requests.get(baike_url+entity,headers=headers).text
            print('baike = ' ,sogou_baike)

    except Exception as e:
        print('Exception e', e)

tryRequest()